import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:photo_frame/mixin/auto_hide_loading.dart';
import 'package:photo_frame/net/http_manager.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/user/user_manager.dart';
import 'package:photo_frame/widgets/app_bar_widget.dart';
import 'package:provider/provider.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class ChangePasswordPage extends StatefulWidget {
  final Map<String, dynamic>? args;
  ChangePasswordPage(this.args, {super.key});

  @override
  State<StatefulWidget> createState() => ChangePasswordState();
}

class ChangePasswordState extends State<ChangePasswordPage>
    with AutoHideLoading {
  late Map<String, dynamic>? args;
  TextEditingController password1Controller = TextEditingController();
  TextEditingController password2Controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    args = widget.args;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: commonAppBar(AppLocalizations.of(context)!.changePassword),
      body: ChangeNotifierProvider(
        create: (context) => ChangePasswordViewModel(),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 15),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                margin: const EdgeInsets.only(top: 20),
                child: TextField(
                  controller: password1Controller,
                  style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14),
                  decoration: InputDecoration(
                    hintText: AppLocalizations.of(context)!.enterNewPassword,
                    hintStyle:
                        const TextStyle(color: Color(0xff999999), fontSize: 14),
                    fillColor: Color(0xffEAECEE),
                    contentPadding: const EdgeInsets.symmetric(
                        horizontal: 26, vertical: 18),
                    filled: true,
                    border: OutlineInputBorder(
                      borderSide: BorderSide.none,
                      borderRadius: BorderRadius.circular(28.5),
                    ),
                  ),
                ),
              ),
              Container(
                margin: const EdgeInsets.only(top: 10),
                child: TextField(
                  controller: password2Controller,
                  style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14),
                  decoration: InputDecoration(
                    hintText:
                        AppLocalizations.of(context)!.enterNewPasswordAgain,
                    hintStyle:
                        const TextStyle(color: Color(0xff999999), fontSize: 14),
                    fillColor: Color(0xffEAECEE),
                    contentPadding: const EdgeInsets.symmetric(
                        horizontal: 26, vertical: 18),
                    filled: true,
                    border: OutlineInputBorder(
                      borderSide: BorderSide.none,
                      borderRadius: BorderRadius.circular(28.5),
                    ),
                  ),
                ),
              ),
              Builder(builder: (context) {
                return Opacity(
                  opacity:
                      context.watch<ChangePasswordViewModel>().errMsg != null
                          ? 1
                          : 0,
                  child: Container(
                    margin: const EdgeInsets.only(
                      left: 29,
                      top: 12,
                    ),
                    child: Text(
                      "*${context.watch<ChangePasswordViewModel>().errMsg}",
                      style: TextStyle(
                          color: const Color(0xffFF4747), fontSize: 11),
                    ),
                  ),
                );
              }),
              Builder(builder: (context) {
                return CupertinoButton(
                  padding: EdgeInsets.zero,
                  onPressed: () {
                    context.read<ChangePasswordViewModel>().changePassword(
                        context,
                        args?['email'],
                        password1Controller.text,
                        password2Controller.text);
                  },
                  child: Container(
                    margin: const EdgeInsets.only(top: 79.5),
                    height: 57,
                    decoration: BoxDecoration(
                        color: const Color(0xff3F74EF),
                        borderRadius: BorderRadius.circular(28.5)),
                    child: Center(
                        child: Text(
                      AppLocalizations.of(context)!.confirm,
                      style: TextStyle(
                          color: Colors.white, fontWeight: FontWeight.bold),
                    )),
                  ),
                );
              }),
            ],
          ),
        ),
      ),
    );
  }
}

class ChangePasswordViewModel extends ChangeNotifier {
  String? errMsg;

  changePassword(BuildContext context, String email, String password,
      String password2) async {
    if (password.isEmpty || password2.isEmpty || password != password2) {
      errMsg = AppLocalizations.of(context)!.pleaseCheckYourPassword;
      notifyListeners();
      return;
    }
    errMsg = null;
    await EasyLoading.show(
      maskType: EasyLoadingMaskType.black,
    );
    return HttpManager.instance.doRequest("/user/password",
        parameters: {"email": email, "pwd": password}).then((e) {
      if (e.isSuccess) {
        Fluttertoast.showToast(
            msg: AppLocalizations.of(context)!.modifySuccessful);
        UserManager.instance.logout();
        return true;
      } else {
        Fluttertoast.showToast(
            msg: e.msg ?? AppLocalizations.of(context)!.modifyFailed);
        return true;
      }
    }).catchError((e) {
      Fluttertoast.showToast(msg: AppLocalizations.of(context)!.netError);
      return false;
    }).whenComplete(() {
      EasyLoading.dismiss();
    });
  }
}
